<template>
  <!-- 添加条件渲染，只有登录后才显示内容 -->
  <view v-if="userStore.isLoggedIn" class="dashboard-container">
    <!-- Status bar placeholder -->
    <view :style="{ height: statusBarHeight + 'px' }"></view>
        
        <!-- Page title -->
        <view class="page-header">
          <view class="title-section">
            <text class="page-title">智能货架管理</text>
            <text class="date">{{ currentDate }}</text>
          </view>
          <view class="refresh-btn" @click="refreshData">
            <uni-icons type="refresh" size="18" color="#FF8C42"></uni-icons>
          </view>
        </view>
    
    <!-- Statistics overview -->
    <view class="stats-overview">
      <view class="stats-grid">
        <!-- Total machines -->
        <view class="stat-card">
          <view class="stat-icon machine-icon">
            <uni-icons type="shop" size="24" color="#FF8C42"></uni-icons>
          </view>
          <view class="stat-content">
            <text class="stat-label">贩卖机总数</text>
            <text class="stat-value">{{ dashboardData.totalMachines }}</text>
          </view>
        </view>
        
        <!-- Total products -->
        <view class="stat-card">
          <view class="stat-icon product-icon">
            <uni-icons type="gift" size="24" color="#FF8C42"></uni-icons>
          </view>
          <view class="stat-content">
            <text class="stat-label">商品总数</text>
            <text class="stat-value">{{ dashboardData.totalProducts }}</text>
          </view>
        </view>
        
        <!-- Today's sales -->
        <view class="stat-card">
          <view class="stat-icon sales-icon">
            <uni-icons type="cart" size="24" color="#FF8C42"></uni-icons>
          </view>
          <view class="stat-content">
            <text class="stat-label">今日销量</text>
            <text class="stat-value">{{ dashboardData.todaySales }}</text>
          </view>
        </view>
        
        <!-- Low stock warning -->
        <view class="stat-card">
          <view class="stat-icon warning-icon">
            <uni-icons type="notification" size="24" color="#FF8C42"></uni-icons>
          </view>
          <view class="stat-content">
            <text class="stat-label">库存预警</text>
            <text class="stat-value">{{ lowStockCount }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- Shelves section with search -->
    <view class="shelves-section">
      <view class="section-header">
        <view class="section-title">
          <text>货架管理</text>
        </view>
        <view class="view-all" @click="navigateTo('allShelves')">
          <text>查看全部</text>
          <uni-icons type="right" size="14" color="#999"></uni-icons>
        </view>
      </view>
      
      <!-- Add new shelf button -->
      <view class="add-shelf-btn" @click="showCreateShelfModal = true">
        <uni-icons type="plus" size="16" color="#FFFFFF"></uni-icons>
        <text>创建新货架</text>
      </view>
      
      <!-- Shelf search box -->
      <view class="search-box shelf-search-box">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input 
          type="text" 
          v-model="shelfSearchKeyword" 
          placeholder="搜索货架ID或名称" 
          confirm-type="search"
          @confirm="searchShelf"
        />
        <view v-if="shelfSearchKeyword" class="clear-search" @click="clearShelfSearch">
          <uni-icons type="close" size="14" color="#999"></uni-icons>
        </view>
      </view>
      
      <!-- Shelf search results -->
      <view v-if="shelfSearchResult" class="shelf-search-result">
        <view class="shelf-card" @click="viewShelfDetail(shelfSearchResult.id)">
          <view class="shelf-header">
            <view class="shelf-name">{{ shelfSearchResult.name }}</view>
            <view :class="['shelf-status', shelfSearchResult.status === 1 ? 'status-online' : 'status-offline']">
              {{ shelfSearchResult.status === 1 ? '正常' : '维护中' }}
            </view>
          </view>
          <view class="shelf-location">{{ shelfSearchResult.location }}</view>
          <view class="shelf-stats">
            <view class="shelf-stat">
              <text class="stat-label">容量</text>
              <text class="stat-value">{{ shelfSearchResult.capacity }}</text>
            </view>
            <view class="shelf-stat">
              <text class="stat-label">商家ID</text>
              <text class="stat-value">{{ shelfSearchResult.merchantId }}</text>
            </view>
          </view>
          <view class="stock-bar">
            <view 
              class="stock-progress" 
              :style="{ width: calculateCapacityPercentage(shelfSearchResult) + '%', backgroundColor: getCapacityColor(calculateCapacityPercentage(shelfSearchResult)) }"
            ></view>
          </view>
          <view class="shelf-actions">
            <view class="shelf-action-btn" @click.stop="viewShelfProducts(shelfSearchResult.id)">
              <uni-icons type="list" size="14" color="#FF8C42"></uni-icons>
              <text>查看商品</text>
            </view>
            <view class="shelf-action-btn restock-btn" @click.stop="openRestockModal(shelfSearchResult.id, shelfSearchResult.name)">
              <uni-icons type="plus" size="14" color="#10B981"></uni-icons>
              <text>补货</text>
            </view>
            <view class="shelf-action-btn delete-btn" @click.stop="confirmDeleteShelf(shelfSearchResult.id)">
              <uni-icons type="trash" size="14" color="#EF4444"></uni-icons>
              <text>删除货架</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- Shelf searching status -->
      <view v-else-if="isSearchingShelf" class="search-loading">
        <uni-icons type="spinner-cycle" size="24" color="#FF8C42"></uni-icons>
        <text>搜索中...</text>
      </view>
      
      <!-- No shelf search results -->
      <view v-else-if="shelfSearchKeyword && !shelfSearchResult && !isSearchingShelf" class="no-results">
        <text>未找到相关货架</text>
      </view>
      
      <!-- All shelves list (show when not searching) -->
      <view v-else class="shelves-list">
        <view 
          v-for="shelf in shelves" 
          :key="shelf.id" 
          class="shelf-card"
          @click="viewShelfDetail(shelf.id)"
        >
          <view class="shelf-header">
            <view class="shelf-name">{{ shelf.name }}</view>
            <view :class="['shelf-status', shelf.status === 1 ? 'status-online' : 'status-offline']">
              {{ shelf.status === 1 ? '正常' : '维护中' }}
            </view>
          </view>
          <view class="shelf-location">{{ shelf.location }}</view>
          <view class="shelf-stats">
            <view class="shelf-stat">
              <text class="stat-label">容量</text>
              <text class="stat-value">{{ shelf.capacity }}</text>
            </view>
            <view class="shelf-stat">
              <text class="stat-label">商家ID</text>
              <text class="stat-value">{{ shelf.merchantId }}</text>
            </view>
          </view>
          <view class="stock-bar">
            <view 
              class="stock-progress" 
              :style="{ width: calculateCapacityPercentage(shelf) + '%', backgroundColor: getCapacityColor(calculateCapacityPercentage(shelf)) }"
            ></view>
          </view>
          <view class="shelf-actions">
            <view class="shelf-action-btn" @click.stop="viewShelfProducts(shelf.id)">
              <uni-icons type="list" size="14" color="#FF8C42"></uni-icons>
              <text>查看商品</text>
            </view>
            <view class="shelf-action-btn restock-btn" @click.stop="openRestockModal(shelf.id, shelf.name)">
              <uni-icons type="plus" size="14" color="#10B981"></uni-icons>
              <text>补货</text>
            </view>
            <view class="shelf-action-btn delete-btn" @click.stop="confirmDeleteShelf(shelf.id)">
              <uni-icons type="trash" size="14" color="#EF4444"></uni-icons>
              <text>删除货架</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- Product search section -->
    <view class="products-section">
      <view class="section-header">
        <view class="section-title">
          <text>商品搜索</text>
        </view>
        <view class="view-all" @click="navigateTo('allProducts')">
          <text>查看全部</text>
          <uni-icons type="right" size="14" color="#999"></uni-icons>
        </view>
      </view>
      
      <!-- Search box -->
      <view class="search-box">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input 
          type="text" 
          v-model="searchKeyword" 
          placeholder="搜索商品名称" 
          confirm-type="search"
          @confirm="searchProducts"
        />
        <view v-if="searchKeyword" class="clear-search" @click="clearSearch">
          <uni-icons type="close" size="14" color="#999"></uni-icons>
        </view>
      </view>
      
      <!-- Search results -->
      <view v-if="searchResults.length > 0" class="search-results">
        <view 
          v-for="product in searchResults" 
          :key="product.id" 
          class="search-result-item"
          @click="viewProductDetail(product.id)"
        >
          <image class="result-image" :src="getProductImage(product)" mode="aspectFill"></image>
          <view class="result-info">
            <view class="result-name">{{ product.name }}</view>
            <view class="result-category">{{ product.description }}</view>
          </view>
          <view class="result-price">¥{{ product.price.toFixed(2) }}</view>
        </view>
      </view>
      
      <!-- Searching status -->
      <view v-else-if="isSearching" class="search-loading">
        <uni-icons type="spinner-cycle" size="24" color="#FF8C42"></uni-icons>
        <text>搜索中...</text>
      </view>
      
      <!-- No search results -->
      <view v-else-if="searchKeyword && searchResults.length === 0 && !isSearching" class="no-results">
        <text>未找到相关商品</text>
      </view>
      
      <!-- Product sales comparison section -->
      <view v-else class="products-list">
        <view 
          v-for="(product, index) in topProducts" 
          :key="product.id" 
          class="product-item"
          @click="viewProductDetail(product.id)"
        >
          <!-- Ranking number -->
          <view class="product-rank-container">
            <view class="product-rank">{{ index + 1 }}</view>
          </view>
          
          <!-- Product image -->
          <image class="product-image" :src="getProductImage(product)" mode="aspectFill"></image>
          
          <!-- Product info -->
          <view class="product-info">
            <view class="product-name">{{ product.name }}</view>
            <view class="product-category">{{ product.description }}</view>
            <!-- Sales bar chart -->
            <view class="sales-bar-container">
              <view 
                class="sales-bar" 
                :style="{ width: calculateSalesPercentage(product) + '%' }"
              ></view>
            </view>
          </view>
          
          <!-- Sales quantity -->
          <view class="product-sales">
            <text class="sales-value">{{ product.salesCount || 0 }}</text>
            <text class="sales-label">件</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- Low stock warning products -->
    <view class="warning-section" v-if="lowStockProducts.length > 0">
      <view class="section-header">
        <view class="section-title">
          <text>库存预警商品</text>
        </view>
        <view class="view-all" @click="navigateTo('lowStock')">
          <text>查看全部</text>
          <uni-icons type="right" size="14" color="#999"></uni-icons>
        </view>
      </view>
      
      <view class="warning-list">
        <view 
          v-for="product in lowStockProducts" 
          :key="product.id" 
          class="warning-item"
          @click="replenishStock(product.id)"
        >
          <image class="warning-image" :src="getProductImage(product)" mode="aspectFill"></image>
          <view class="warning-info">
            <view class="warning-name">{{ product.name }}</view>
            <view class="warning-location">{{ getMerchantName(product.merchantId) }}</view>
          </view>
          <view class="warning-stock">
            <text class="warning-value">{{ product.totalStock }}</text>
            <text class="warning-label">剩余</text>
          </view>
          <view class="replenish-btn">补货</view>
        </view>
      </view>
    </view>
    
    <!-- User type manager -->
    <user-type-manager></user-type-manager>
    
    <!-- Bottom navigation bar -->
    <tab-bar :active="0"></tab-bar>
    
    <!-- Shelf Products Modal -->
    <view class="modal-overlay" v-if="showShelfProductsModal" @click="closeShelfProductsModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">货架商品列表 - {{ selectedShelfName }}</text>
          <view class="modal-close" @click="closeShelfProductsModal">
            <uni-icons type="close" size="20" color="#333"></uni-icons>
          </view>
        </view>
        
        <view class="modal-body">
          <!-- Loading state -->
          <view v-if="isLoadingShelfProducts" class="modal-loading">
            <uni-icons type="spinner-cycle" size="24" color="#FF8C42"></uni-icons>
            <text>加载中...</text>
          </view>
          
          <!-- Error state -->
          <view v-else-if="shelfProductsError" class="modal-error">
            <uni-icons type="info" size="24" color="#EF4444"></uni-icons>
            <text>{{ shelfProductsError }}</text>
            <view class="retry-btn" @click="retryLoadShelfProducts">
              <text>重试</text>
            </view>
          </view>
          
          <!-- Empty state -->
          <view v-else-if="shelfProducts.length === 0" class="modal-empty">
            <uni-icons type="info" size="24" color="#999"></uni-icons>
            <text>该货架暂无商品</text>
          </view>
          
          <!-- Products list -->
          <view v-else class="shelf-products-list">
            <view 
              v-for="product in shelfProducts" 
              :key="product.id" 
              class="shelf-product-item"
              @click="viewProductDetail(product.productId || product.id)"
            >
              <image class="shelf-product-image" :src="getProductImage(product)" mode="aspectFill"></image>
              <view class="shelf-product-info">
                <view class="shelf-product-name">{{ product.name }}</view>
                <view class="shelf-product-description">{{ product.description }}</view>
                <view class="shelf-product-details">
                  <view class="shelf-product-price">¥{{ (product.price || 0).toFixed(2) }}</view>
                  <view class="shelf-product-stock">
                    <text>货架库存: </text>
                    <text :class="{'low-stock': product.quantity <= 5}">
                      {{ product.quantity || 0 }}
                    </text>
                  </view>
                  <view v-if="product.position" class="shelf-product-position">
                    <text>位置: {{ product.position }}</text>
                  </view>
                </view>
              </view>
              <view class="shelf-product-actions">
                <view class="shelf-product-action-btn" @click.stop="openSingleProductRestockModal(product)">
                  <uni-icons type="plus" size="12" color="#10B981"></uni-icons>
                  <text>补货</text>
                </view>
                <view class="shelf-product-action-btn remove-btn" @click.stop="confirmRemoveProduct(product)">
                  <uni-icons type="minus" size="12" color="#EF4444"></uni-icons>
                  <text>移除</text>
                </view>
              </view>
            </view>
          </view>
          
          <!-- Pagination -->
          <view v-if="shelfProductsPagination.total > 0" class="modal-pagination">
            <view class="pagination-info">
              <text>共 {{ shelfProductsPagination.total }} 条记录，第 {{ shelfProductsPagination.current }} / {{ shelfProductsPagination.pages }} 页</text>
            </view>
            <view class="pagination-controls">
              <view 
                class="pagination-btn" 
                :class="{'disabled': shelfProductsPagination.current <= 1}"
                @click="loadShelfProductsPage(shelfProductsPagination.current - 1)"
              >
                <text>上一页</text>
              </view>
              <view 
                class="pagination-btn" 
                :class="{'disabled': shelfProductsPagination.current >= shelfProductsPagination.pages}"
                @click="loadShelfProductsPage(shelfProductsPagination.current + 1)"
              >
                <text>下一页</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- Restock Modal -->
    <view class="modal-overlay" v-if="showRestockModal" @click="closeRestockModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">货架补货 - {{ restockShelfName }}</text>
          <view class="modal-close" @click="closeRestockModal">
            <uni-icons type="close" size="20" color="#333"></uni-icons>
          </view>
        </view>
        
        <view class="modal-body">
          <!-- Product selection -->
          <view class="form-group">
            <text class="form-label">选择商品</text>
            <view class="product-selector" @click="showProductSelector = true">
              <text v-if="restockForm.productId" class="selected-product">
                {{ getSelectedProductName() }}
              </text>
              <text v-else class="placeholder-text">请选择要补货的商品</text>
              <uni-icons type="right" size="16" color="#999"></uni-icons>
            </view>
          </view>
          
          <!-- Quantity input -->
          <view class="form-group">
            <text class="form-label">补货数量</text>
            <input 
              type="number" 
              v-model="restockForm.quantity" 
              placeholder="请输入补货数量"
              class="form-input"
              :disabled="!restockForm.productId"
            />
          </view>
          
          <!-- Position input -->
          <view class="form-group">
            <text class="form-label">货架位置（可选）</text>
            <input 
              type="text" 
              v-model="restockForm.position" 
              placeholder="请输入货架位置编码"
              class="form-input"
              :disabled="!restockForm.productId"
            />
          </view>
          
          <!-- Remarks input -->
          <view class="form-group">
            <text class="form-label">备注（可选）</text>
            <textarea 
              v-model="restockForm.remarks" 
              placeholder="请输入补货备注"
              class="form-textarea"
              :disabled="!restockForm.productId"
            ></textarea>
          </view>
          
          <view class="form-actions">
            <view class="form-btn cancel-btn" @click="closeRestockModal">
              <text>取消</text>
            </view>
            <view 
              class="form-btn submit-btn" 
              :class="{'disabled': !canSubmitRestock}"
              @click="submitRestock"
            >
              <text>确认补货</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- Product Selector Modal -->
    <view class="modal-overlay" v-if="showProductSelector" @click="showProductSelector = false">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">选择商品</text>
          <view class="modal-close" @click="showProductSelector = false">
            <uni-icons type="close" size="20" color="#333"></uni-icons>
          </view>
        </view>
        
        <view class="modal-body">
          <!-- Product search -->
          <view class="search-box">
            <uni-icons type="search" size="16" color="#999"></uni-icons>
            <input 
              type="text" 
              v-model="productSearchKeyword" 
              placeholder="搜索商品名称" 
              confirm-type="search"
              @input="searchProductsForRestock"
            />
            <view v-if="productSearchKeyword" class="clear-search" @click="clearProductSearch">
              <uni-icons type="close" size="14" color="#999"></uni-icons>
            </view>
          </view>
          
          <!-- Product list -->
          <view class="product-selector-list">
            <view 
              v-for="product in availableProducts" 
              :key="product.id" 
              class="product-selector-item"
              @click="selectProduct(product)"
            >
              <image class="product-selector-image" :src="getProductImage(product)" mode="aspectFill"></image>
              <view class="product-selector-info">
                <view class="product-selector-name">{{ product.name }}</view>
                <view class="product-selector-description">{{ product.description }}</view>
                <view class="product-selector-price">¥{{ product.price.toFixed(2) }}</view>
                <view class="product-selector-stock">库存: {{ product.totalStock }}</view>
              </view>
              <view v-if="restockForm.productId === product.id" class="product-selected-icon">
                <uni-icons type="checkmarkempty" size="20" color="#10B981"></uni-icons>
              </view>
            </view>
          </view>
          
          <!-- Empty state -->
          <view v-if="availableProducts.length === 0" class="modal-empty">
            <uni-icons type="info" size="24" color="#999"></uni-icons>
            <text>暂无可选商品</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- Create Shelf Modal -->
    <view class="modal-overlay" v-if="showCreateShelfModal" @click="showCreateShelfModal = false">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">创建新货架</text>
          <view class="modal-close" @click="showCreateShelfModal = false">
            <uni-icons type="close" size="20" color="#333"></uni-icons>
          </view>
        </view>
        
        <view class="modal-body">
          <view class="form-group">
            <text class="form-label">货架名称</text>
            <input 
              type="text" 
              v-model="newShelf.name" 
              placeholder="请输入货架名称"
              class="form-input"
            />
          </view>
          
          <view class="form-group">
            <text class="form-label">位置</text>
            <input 
              type="text" 
              v-model="newShelf.location" 
              placeholder="请输入货架位置"
              class="form-input"
            />
          </view>
          
          <view class="form-group">
            <text class="form-label">容量</text>
            <input 
              type="number" 
              v-model="newShelf.capacity" 
              placeholder="请输入货架容量"
              class="form-input"
            />
          </view>
          
          <view class="form-group">
            <text class="form-label">商家ID</text>
            <input 
              type="number" 
              v-model="newShelf.merchantId" 
              placeholder="请输入商家ID"
              class="form-input"
            />
          </view>
          
          <view class="form-group">
            <text class="form-label">状态</text>
            <view class="radio-group">
              <view class="radio-item" @click="newShelf.status = 1">
                <view class="radio-button" :class="{'radio-selected': newShelf.status === 1}"></view>
                <text>正常</text>
              </view>
              <view class="radio-item" @click="newShelf.status = 0">
                <view class="radio-button" :class="{'radio-selected': newShelf.status === 0}"></view>
                <text>维护中</text>
              </view>
            </view>
          </view>
          
          <view class="form-actions">
            <view class="form-btn cancel-btn" @click="showCreateShelfModal = false">
              <text>取消</text>
            </view>
            <view class="form-btn submit-btn" @click="createShelf">
              <text>创建</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- Delete Confirmation Modal -->
    <view class="modal-overlay" v-if="showDeleteConfirmModal" @click="showDeleteConfirmModal = false">
      <view class="modal-content confirm-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">删除确认</text>
          <view class="modal-close" @click="showDeleteConfirmModal = false">
            <uni-icons type="close" size="20" color="#333"></uni-icons>
          </view>
        </view>
        
        <view class="modal-body">
          <view class="confirm-message">
            <uni-icons type="info" size="24" color="#EF4444"></uni-icons>
            <text>确定要删除该货架吗？此操作不可恢复。</text>
          </view>
          
          <view class="form-actions">
            <view class="form-btn cancel-btn" @click="showDeleteConfirmModal = false">
              <text>取消</text>
            </view>
            <view class="form-btn delete-confirm-btn" @click="deleteShelf">
              <text>确认删除</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- Remove Product Modal -->
    <view class="modal-overlay" v-if="showRemoveProductModal" @click="closeRemoveProductModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">移除商品 - {{ removeProductForm.productName }}</text>
          <view class="modal-close" @click="closeRemoveProductModal">
            <uni-icons type="close" size="20" color="#333"></uni-icons>
          </view>
        </view>
        
        <view class="modal-body">
          <!-- Current quantity info -->
          <view class="form-group">
            <text class="form-label">当前库存</text>
            <view class="quantity-info">
              <text class="quantity-value">{{ removeProductForm.currentQuantity }}</text>
              <text class="quantity-unit">件</text>
            </view>
          </view>
          
          <!-- Remove quantity input -->
          <view class="form-group">
            <text class="form-label">移除数量</text>
            <input 
              type="number" 
              v-model="removeProductForm.removeQuantity" 
              placeholder="请输入移除数量"
              class="form-input"
              :max="removeProductForm.currentQuantity"
              min="1"
            />
            <text class="form-hint">最多可移除 {{ removeProductForm.currentQuantity }} 件</text>
          </view>
          
          <!-- Reason input -->
          <view class="form-group">
            <text class="form-label">移除原因</text>
            <textarea 
              v-model="removeProductForm.reason" 
              placeholder="请输入移除原因（可选）"
              class="form-textarea"
            ></textarea>
          </view>
          
          <!-- RFID tags section -->
          <view class="form-group">
            <text class="form-label">RFID标签（可选）</text>
            <view class="rfid-input-section">
              <input 
                type="text" 
                v-model="removeProductForm.newRfidTag" 
                placeholder="输入RFID标签"
                class="form-input rfid-input"
              />
              <view class="add-rfid-btn" @click="addRfidTag">
                <uni-icons type="plus" size="16" color="#10B981"></uni-icons>
                <text>添加</text>
              </view>
            </view>
            
            <!-- RFID tags list -->
            <view v-if="removeProductForm.rfidTags.length > 0" class="rfid-tags-list">
              <view 
                v-for="(tag, index) in removeProductForm.rfidTags" 
                :key="index" 
                class="rfid-tag-item"
              >
                <text class="rfid-tag-text">{{ tag }}</text>
                <view class="remove-rfid-btn" @click="removeRfidTag(index)">
                  <uni-icons type="close" size="14" color="#EF4444"></uni-icons>
                </view>
              </view>
            </view>
          </view>
          
          <view class="form-actions">
            <view class="form-btn cancel-btn" @click="closeRemoveProductModal">
              <text>取消</text>
            </view>
            <view 
              class="form-btn remove-confirm-btn" 
              @click="submitRemoveProduct"
            >
              <text>确认移除</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
   <!-- 未登录时显示的内容 -->
  <view v-else class="login-required-container">
      <view class="login-required-content">
        <uni-icons type="locked" size="64" color="#FF8C42"></uni-icons>
        <text class="login-required-title">请先登录</text>
        <text class="login-required-desc">您需要登录后才能访问智能货架管理系统</text>
        <view class="login-btn" @click="navigateToLogin">
          <text>去登录</text>
        </view>
      </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useUserStore } from '@/store/user';
import { useProductStore } from '@/store/product';
import UserTypeManager from '@/components/user-type-manager.vue';
import TabBar from '@/components/tab-bar.vue';
import http from '@/utils/http/http.js';
import { BASE_URL } from '@/config/env';

// Status bar height
const statusBarHeight = ref(0);
// User store
const userStore = useUserStore();
// Product store
const productStore = useProductStore();
// Search keyword
const searchKeyword = ref('');
// Search results
const searchResults = ref([]);
// Is searching
const isSearching = ref(false);
// Top products
const topProducts = ref([]);
// Low stock products
const lowStockProducts = ref([]);
// Shelves data
const shelves = ref([]);

// Shelf search variables
const shelfSearchKeyword = ref('');
const shelfSearchResult = ref(null);
const isSearchingShelf = ref(false);

// Shelf products modal variables
const showShelfProductsModal = ref(false);
const selectedShelfId = ref(null);
const selectedShelfName = ref('');
const shelfProducts = ref([]);
const isLoadingShelfProducts = ref(false);
const shelfProductsError = ref(null);

const navigateToLogin = () => {
  uni.navigateTo({
    url: '/pages/merchant/settings',
    fail: () => {
      uni.showToast({
        title: '登录页面不存在，请检查路径',
        icon: 'none'
      });
    }
  });
};

// 货架商品分页信息
const shelfProductsPagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  pages: 0
});

// Restock modal variables
const showRestockModal = ref(false);
const restockShelfId = ref(null);
const restockShelfName = ref('');
const restockForm = reactive({
  productId: null,
  quantity: 1,
  position: '',
  remarks: ''
});

// Product selector variables
const showProductSelector = ref(false);
const productSearchKeyword = ref('');
const availableProducts = ref([]);
const allProducts = ref([]);

// Create shelf modal variables
const showCreateShelfModal = ref(false);
const newShelf = reactive({
  name: '',
  location: '',
  capacity: 100,
  merchantId: 1,
  status: 1
});

// Delete confirmation modal variables
const showDeleteConfirmModal = ref(false);
const shelfToDelete = ref(null);

// Remove product modal variables
const showRemoveProductModal = ref(false);
const removeProductForm = reactive({
  shelfId: null,
  productId: null,
  productName: '',
  currentQuantity: 0,
  removeQuantity: 1,
  reason: '',
  rfidTags: [],
  newRfidTag: ''
});

// Merchant mapping
const merchantMap = ref({
  1: '智能货架 #A001',
  2: '智能货架 #A002',
  3: '智能货架 #B001'
});

// Computed properties
const canSubmitRestock = computed(() => {
  return restockForm.productId && restockForm.quantity > 0;
});

// Get status bar height
const getStatusBarHeight = () => {
  try {
    const systemInfo = uni.getSystemInfoSync();
    statusBarHeight.value = systemInfo.statusBarHeight || 0;
  } catch (e) {
    console.error('获取系统信息失败:', e);
    statusBarHeight.value = 0;
  }
};

// Get current date
const currentDate = computed(() => {
  const now = new Date();
  const year = now.getFullYear();
  const month = now.getMonth() + 1;
  const day = now.getDate();
  return `${year}年${month}月${day}日`;
});

// Low stock product count
const lowStockCount = computed(() => {
  return lowStockProducts.value.length;
});

// Dashboard data (partially static data)
const dashboardData = reactive({
  totalMachines: 12,
  totalProducts: 0,
  todaySales: 243,

  // Machine data
  machines: [
    {
      id: 1,
      name: '智能货架 #A001',
      location: '科技园区1号楼大厅',
      status: 'online',
      productCount: 24,
      stockPercentage: 85,
      todaySales: 42
    },
    {
      id: 2,
      name: '智能货架 #A002',
      location: '科技园区2号楼一层',
      status: 'online',
      productCount: 18,
      stockPercentage: 62,
      todaySales: 36
    },
    {
      id: 3,
      name: '智能货架 #B001',
      location: '商业中心购物广场',
      status: 'online',
      productCount: 32,
      stockPercentage: 91,
      todaySales: 78
    },
    {
      id: 4,
      name: '智能货架 #B002',
      location: '商业中心地下一层',
      status: 'offline',
      productCount: 12,
      stockPercentage: 45,
      todaySales: 23
    },
    {
      id: 5,
      name: '智能货架 #C001',
      location: '创业园区3号楼',
      status: 'online',
      productCount: 28,
      stockPercentage: 76,
      todaySales: 64
    }
  ]
});

// Get product image
const getProductImage = (product) => {
  if (product.mainImageUrl) {
    if (product.mainImageUrl.startsWith('/')) {
      // const BASE_URL = 'http://localhost:8080';
	  // const BASE_URL = 'http://192.168.137.1:8080';
      return `${BASE_URL}${product.mainImageUrl}`;
    }
    return product.mainImageUrl;
  }
  return `/placeholder.svg?height=120&width=120&text=${encodeURIComponent(product.name)}`;
};

// Get merchant name
const getMerchantName = (merchantId) => {
  return merchantMap.value[merchantId] || '未知货架';
};

// Get stock color
const getStockColor = (percentage) => {
  if (percentage >= 70) return '#10B981'; // Green
  if (percentage >= 30) return '#F59E0B'; // Yellow
  return '#EF4444'; // Red
};

// Calculate capacity percentage
const calculateCapacityPercentage = (shelf) => {
  // This is a placeholder calculation since we don't have actual usage data
  // You would replace this with real data from your API
  return Math.floor(Math.random() * 50) + 50; // Random value between 50-100%
};

// Get capacity color
const getCapacityColor = (percentage) => {
  if (percentage >= 70) return '#10B981'; // Green
  if (percentage >= 30) return '#F59E0B'; // Yellow
  return '#EF4444'; // Red
};

// Calculate sales percentage
const calculateSalesPercentage = (product) => {
  const maxSales = Math.max(...topProducts.value.map(p => p.salesCount || 0));
  if (maxSales === 0) return 0;
  return ((product.salesCount || 0) / maxSales) * 100;
};

// Get selected product name
const getSelectedProductName = () => {
  const product = allProducts.value.find(p => p.id === restockForm.productId);
  return product ? product.name : '';
};

// Clear product search
const clearSearch = () => {
  searchKeyword.value = '';
  searchResults.value = [];
};

// Clear shelf search
const clearShelfSearch = () => {
  shelfSearchKeyword.value = '';
  shelfSearchResult.value = null;
};

// Clear product search for restock
const clearProductSearch = () => {
  productSearchKeyword.value = '';
  availableProducts.value = [...allProducts.value];
};

// Search shelf by ID or name
const searchShelf = async () => {
  if (!shelfSearchKeyword.value.trim()) {
    shelfSearchResult.value = null;
    return;
  }
  
  isSearchingShelf.value = true;
  
  try {
    // First try to search by ID if the input is a number
    if (!isNaN(shelfSearchKeyword.value) && shelfSearchKeyword.value.trim() !== '') {
      const shelfId = parseInt(shelfSearchKeyword.value.trim());
      const response = await http.get(`/api/shelves/${shelfId}`);
      
      if (response.code === 200 && response.data) {
        // 如果返回的是包含shelf的对象，提取shelf数据
        shelfSearchResult.value = response.data.shelf || response.data;
        isSearchingShelf.value = false;
        return;
      }
    }
    
    // If not found by ID or input is not a number, search in the existing shelves by name
    const matchedShelf = shelves.value.find(shelf => 
      shelf.name.toLowerCase().includes(shelfSearchKeyword.value.toLowerCase())
    );
    
    if (matchedShelf) {
      shelfSearchResult.value = matchedShelf;
    } else {
      shelfSearchResult.value = null;
      uni.showToast({
        title: '未找到相关货架',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('搜索货架失败:', error);
    shelfSearchResult.value = null;
    uni.showToast({
      title: '搜索失败，请重试',
      icon: 'none'
    });
  } finally {
    isSearchingShelf.value = false;
  }
};

// Search products
const searchProducts = async () => {
  if (!searchKeyword.value.trim()) {
    searchResults.value = [];
    return;
  }
  
  isSearching.value = true;
  
  try {
    const response = await http.get('/api/products/search', {
      keyword: searchKeyword.value,
      limit: 20
    });
    
    if (response.code === 200 && response.data) {
      searchResults.value = response.data;
    } else {
      searchResults.value = [];
      uni.showToast({
        title: response.msg || '搜索失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('搜索商品失败:', error);
    searchResults.value = [];
    uni.showToast({
      title: '搜索失败，请重试',
      icon: 'none'
    });
  } finally {
    isSearching.value = false;
  }
};

// Search products for restock
const searchProductsForRestock = () => {
  if (!productSearchKeyword.value.trim()) {
    availableProducts.value = [...allProducts.value];
    return;
  }
  
  const keyword = productSearchKeyword.value.toLowerCase();
  availableProducts.value = allProducts.value.filter(product => 
    product.name.toLowerCase().includes(keyword) ||
    product.description.toLowerCase().includes(keyword)
  );
};

// Select product for restock
const selectProduct = (product) => {
  restockForm.productId = product.id;
  showProductSelector.value = false;
};

// Open restock modal
const openRestockModal = async (shelfId, shelfName) => {
  restockShelfId.value = shelfId;
  restockShelfName.value = shelfName;
  
  // Reset form
  restockForm.productId = null;
  restockForm.quantity = 1;
  restockForm.position = '';
  restockForm.remarks = '';
  
  // 重新获取最新的商品数据，确保补货时能看到所有商品
  await fetchAllProducts();
  
  // Load available products
  availableProducts.value = [...allProducts.value];
  productSearchKeyword.value = '';
  
  showRestockModal.value = true;
};

// Open single product restock modal
const openSingleProductRestockModal = (product) => {
  restockShelfId.value = selectedShelfId.value;
  restockShelfName.value = selectedShelfName.value;
  
  // Pre-fill form with product
  restockForm.productId = product.productId || product.id;
  restockForm.quantity = 1;
  restockForm.position = product.position || '';
  restockForm.remarks = '';
  
  // Close shelf products modal
  closeShelfProductsModal();
  
  showRestockModal.value = true;
};

// Close restock modal
const closeRestockModal = () => {
  showRestockModal.value = false;
  restockShelfId.value = null;
  restockShelfName.value = '';
  
  // Reset form
  restockForm.productId = null;
  restockForm.quantity = 1;
  restockForm.position = '';
  restockForm.remarks = '';
};

// Submit restock
const submitRestock = async () => {
  if (!canSubmitRestock.value) {
    uni.showToast({
      title: '请完善补货信息',
      icon: 'none'
    });
    return;
  }
  
  uni.showLoading({
    title: '补货中...'
  });
  
  try {
    const restockData = {
      productId: restockForm.productId,
      quantity: parseInt(restockForm.quantity),
      position: restockForm.position || null,
      remarks: restockForm.remarks || null
    };
    
    console.log('补货请求数据:', restockData);
    
    const response = await http.post(`/api/shelves/${restockShelfId.value}/restock`, restockData);
    
    console.log('补货响应:', response);
    
    if (response.code === 200) {
      uni.showToast({
        title: '补货成功',
        icon: 'success'
      });
      
      // Close modal
      closeRestockModal();
      
      // Refresh data if needed
      if (showShelfProductsModal.value && selectedShelfId.value === restockShelfId.value) {
        // Refresh shelf products
        fetchShelfProducts(selectedShelfId.value, shelfProductsPagination.current);
      }
      
    } else {
      uni.showToast({
        title: response.msg || '补货失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('补货失败:', error);
    uni.showToast({
      title: '补货失败，请重试',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// Fetch shelves data
const fetchShelves = async () => {
  try {
    const response = await http.get('/api/shelves');
    
    if (response.code === 200 && response.data) {
      shelves.value = response.data.list || [];
      console.log("Fetched shelves:", shelves.value);
      return shelves.value;
    } else {
      console.error('获取货架列表失败:', response.msg);
      return [];
    }
  } catch (error) {
    console.error('获取货架列表请求失败:', error);
    return [];
  }
};

// Create a new shelf
const createShelf = async () => {
  // Validate form
  if (!newShelf.name.trim()) {
    uni.showToast({
      title: '请输入货架名称',
      icon: 'none'
    });
    return;
  }
  
  if (!newShelf.location.trim()) {
    uni.showToast({
      title: '请输入货架位置',
      icon: 'none'
    });
    return;
  }
  
  if (!newShelf.capacity || newShelf.capacity <= 0) {
    uni.showToast({
      title: '请输入有效的货架容量',
      icon: 'none'
    });
    return;
  }
  
  if (!newShelf.merchantId || newShelf.merchantId <= 0) {
    uni.showToast({
      title: '请输入有效的商家ID',
      icon: 'none'
    });
    return;
  }
  
  uni.showLoading({
    title: '创建中...'
  });
  
  try {
    const response = await http.post('/api/shelves', newShelf);
    
    if (response.code === 200) {
      uni.showToast({
        title: '创建成功',
        icon: 'success'
      });
      
      // Reset form
      newShelf.name = '';
      newShelf.location = '';
      newShelf.capacity = 100;
      newShelf.merchantId = 1;
      newShelf.status = 1;
      
      // Close modal
      showCreateShelfModal.value = false;
      
      // Refresh shelves list
      await fetchShelves();
    } else {
      uni.showToast({
        title: response.msg || '创建失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('创建货架失败:', error);
    uni.showToast({
      title: '创建失败，请重试',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// Confirm delete shelf
const confirmDeleteShelf = (shelfId) => {
  shelfToDelete.value = shelfId;
  showDeleteConfirmModal.value = true;
};

// Delete a shelf
const deleteShelf = async () => {
  if (!shelfToDelete.value) return;
  
  uni.showLoading({
    title: '删除中...'
  });
  
  try {
    const response = await http.delete(`/api/shelves/${shelfToDelete.value}`);
    
    if (response.code === 200) {
      uni.showToast({
        title: '删除成功',
        icon: 'success'
      });
      
      // Remove from shelves list
      shelves.value = shelves.value.filter(shelf => shelf.id !== shelfToDelete.value);
      
      // Clear search result if it was the deleted shelf
      if (shelfSearchResult.value && shelfSearchResult.value.id === shelfToDelete.value) {
        shelfSearchResult.value = null;
      }
      
      // Close modal
      showDeleteConfirmModal.value = false;
      shelfToDelete.value = null;
    } else {
      uni.showToast({
        title: response.msg || '删除失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('删除货架失败:', error);
    uni.showToast({
      title: '删除失败，请重试',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// View shelf detail
const viewShelfDetail = (shelfId) => {
  uni.navigateTo({
    url: `/pages/merchant/shelves/detail?id=${shelfId}`,
    fail: () => {
      uni.showToast({
        title: `查看货架ID: ${shelfId}`,
        icon: 'none'
      });
    }
  });
};

// View shelf products - 修改后的实现
const viewShelfProducts = (shelfId) => {
  // 找到对应的货架信息
  const shelf = shelves.value.find(s => s.id === shelfId) || 
                (shelfSearchResult.value && shelfSearchResult.value.id === shelfId ? shelfSearchResult.value : null);
  
  selectedShelfId.value = shelfId;
  selectedShelfName.value = shelf ? shelf.name : `货架 #${shelfId}`;
  
  // 重置分页信息
  shelfProductsPagination.current = 1;
  shelfProductsPagination.total = 0;
  shelfProductsPagination.pages = 0;
  
  showShelfProductsModal.value = true;
  fetchShelfProducts(shelfId, 1);
};

// Fetch shelf products - 修改后的实现
const fetchShelfProducts = async (shelfId, pageNum = 1) => {
  isLoadingShelfProducts.value = true;
  shelfProductsError.value = null;
  
  try {
    const response = await http.get(`/api/shelves/${shelfId}/products`, {
      params: {
        pageNum: pageNum,
        pageSize: shelfProductsPagination.pageSize
      }
    });
    
    console.log(`货架 ${shelfId} 商品查询响应:`, response);
    
    if (response.code === 200) {
      const data = response.data;
      
      // 处理分页数据
      if (data && typeof data === 'object') {
        // 如果返回的是分页对象
        if (data.list) {
          shelfProducts.value = data.list;
          shelfProductsPagination.current = data.pageNum || pageNum;
          shelfProductsPagination.total = data.total || 0;
          shelfProductsPagination.pages = data.pages || Math.ceil((data.total || 0) / shelfProductsPagination.pageSize);
        } 
        // 如果返回的是数组
        else if (Array.isArray(data)) {
          shelfProducts.value = data;
          shelfProductsPagination.current = 1;
          shelfProductsPagination.total = data.length;
          shelfProductsPagination.pages = 1;
        }
        // 如果返回的是其他格式
        else {
          shelfProducts.value = [];
          shelfProductsPagination.current = 1;
          shelfProductsPagination.total = 0;
          shelfProductsPagination.pages = 0;
        }
      } else {
        shelfProducts.value = [];
        shelfProductsPagination.current = 1;
        shelfProductsPagination.total = 0;
        shelfProductsPagination.pages = 0;
      }
      
      console.log(`货架 ${shelfId} 商品列表:`, shelfProducts.value);
      console.log('分页信息:', shelfProductsPagination);
      
    } else {
      shelfProductsError.value = response.msg || '获取货架商品失败';
      console.error('获取货架商品失败:', response.msg);
    }
  } catch (error) {
    shelfProductsError.value = '网络请求失败，请重试';
    console.error('获取货架商品请求失败:', error);
  } finally {
    isLoadingShelfProducts.value = false;
  }
};

// 加载指定页的货架商品
const loadShelfProductsPage = (pageNum) => {
  if (pageNum < 1 || pageNum > shelfProductsPagination.pages) {
    return;
  }
  
  if (selectedShelfId.value) {
    fetchShelfProducts(selectedShelfId.value, pageNum);
  }
};

// Retry loading shelf products
const retryLoadShelfProducts = () => {
  if (selectedShelfId.value) {
    fetchShelfProducts(selectedShelfId.value, shelfProductsPagination.current);
  }
};

// Close shelf products modal
const closeShelfProductsModal = () => {
  showShelfProductsModal.value = false;
  selectedShelfId.value = null;
  selectedShelfName.value = '';
  shelfProducts.value = [];
  shelfProductsError.value = null;
  
  // 重置分页信息
  shelfProductsPagination.current = 1;
  shelfProductsPagination.total = 0;
  shelfProductsPagination.pages = 0;
};

// 修改后的获取商品数据函数 - 统一使用商家商品接口
const fetchAllProducts = async () => {
  try {
    // 确保用户已登录且是商家
    if (!userStore.isLoggedIn || !userStore.isMerchant()) {
      console.error('用户未登录或不是商家');
      return [];
    }
    
    // 优先使用商家专用API获取商品，与orders页面保持一致
    let response;
    try {
      response = await http.get(BASE_URL +'/api/merchant/products', {
        header: {
          'Authorization': `Bearer ${userStore.token || ''}`
        }
      });
    } catch (merchantError) {
      console.warn('商家API调用失败，尝试使用通用API:', merchantError);
      // 如果商家API失败，回退到通用API
      response = await http.get('/api/products/all');
    }
    
    if (response.code === 200 && response.data) {
      let products = [];
      
      // 处理返回的数据格式
      if (Array.isArray(response.data)) {
        products = response.data;
      } else if (typeof response.data === 'object' && response.data !== null) {
        products = response.data.products || response.data.list || [];
      }
      
      // 确保商品数据格式正确
      products = products.map(product => ({
        ...product,
        price: parseFloat(product.price) || 0,
        totalStock: parseInt(product.totalStock) || 0,
        safeStock: parseInt(product.safeStock) || 0
      }));
      
      productStore.setProducts(products);
      allProducts.value = products;
      availableProducts.value = products;
      dashboardData.totalProducts = products.length;
      
      console.log("获取到的商品数据:", products);
      console.log("商品总数:", products.length);
      
      // Process low stock products
      processLowStockProducts(products);
      
      // Process top products (assuming backend doesn't provide sales sorting, frontend simulation)
      processTopProducts(products);
      
      return products;
    } else {
      console.error('获取商品列表失败:', response.msg);
      uni.showToast({
        title: response.msg || '获取商品数据失败',
        icon: 'none'
      });
      return [];
    }
  } catch (error) {
    console.error('获取商品列表请求失败:', error);
    uni.showToast({
      title: '网络错误，请稍后重试',
      icon: 'none'
    });
    return [];
  }
};

// Process low stock products
const processLowStockProducts = (products) => {
  // Filter products with stock below safety stock
  lowStockProducts.value = products.filter(product => 
    product.totalStock <= product.safeStock
  ).sort((a, b) => a.totalStock - b.totalStock);
};

// Process top products (simulate sales data)
const processTopProducts = (products) => {
  // Add simulated sales to products
  const productsWithSales = products.map(product => {
    return {
      ...product,
      salesCount: Math.floor(Math.random() * 100) // Simulate sales data
    };
  });
  
  // Sort by sales and take top 5
  topProducts.value = productsWithSales
    .sort((a, b) => b.salesCount - a.salesCount)
    .slice(0, 5);
};

// Refresh data
const refreshData = async () => {
  uni.showLoading({
    title: '刷新中...'
  });

  try {
    // Refresh product data
    await fetchAllProducts();
    
    // Refresh shelves data
    await fetchShelves();
    
    // Clear any search results
    clearShelfSearch();
    
    // Randomly update today's sales
    dashboardData.todaySales = Math.floor(Math.random() * 50) + 200;

    // Randomly update machine sales
    dashboardData.machines.forEach(machine => {
      machine.todaySales = Math.floor(Math.random() * 20) + 20;
      machine.stockPercentage = Math.floor(Math.random() * 30) + 70;
    });

    uni.showToast({
      title: '数据已刷新',
      icon: 'success'
    });
  } catch (error) {
    console.error('刷新数据失败:', error);
    uni.showToast({
      title: '刷新失败，请重试',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// Page navigation
const navigateTo = (page) => {
  const pageMap = {
    'allMachines': '/pages/merchant/machines/list',
    'allProducts': '/pages/merchant/products/list',
    'lowStock': '/pages/merchant/inventory/low-stock',
    'allShelves': '/pages/merchant/shelves/list'
  };

  const url = pageMap[page];
  if (url) {
    uni.navigateTo({
      url: url,
      fail: () => {
        uni.showToast({
          title: '页面开发中',
          icon: 'none'
        });
      }
    });
  }
};

// View machine detail
const viewMachineDetail = (machineId) => {
  uni.navigateTo({
    url: `/pages/merchant/machines/detail?id=${machineId}`,
    fail: () => {
      uni.showToast({
        title: `查看贩卖机ID: ${machineId}`,
        icon: 'none'
      });
    }
  });
};

// View product detail
const viewProductDetail = (productId) => {
  // Set current selected product
  const product = productStore.getProductById(productId);
  if (product) {
    productStore.setCurrentProduct(product);
    
    uni.navigateTo({
      url: `/pages/merchant/products/detail?id=${productId}`,
      fail: () => {
        // If page doesn't exist, show simple product info
        uni.showModal({
          title: product.name,
          content: `价格: ¥${product.price.toFixed(2)}\n描述: ${product.description}\n库存: ${product.totalStock}`,
          showCancel: false
        });
      }
    });
  } else {
    uni.showToast({
      title: '商品不存在',
      icon: 'none'
    });
  }
};

// Replenish stock
const replenishStock = (productId) => {
  const product = productStore.getProductById(productId);
  if (!product) {
    uni.showToast({
      title: '商品不存在',
      icon: 'none'
    });
    return;
  }
  
  uni.showModal({
    title: '补货确认',
    content: `是否确认为"${product.name}"补货？`,
    success: (res) => {
      if (res.confirm) {
        // Should call replenish API, simulating success here
        uni.showLoading({
          title: '处理中...'
        });
        
        setTimeout(() => {
          // Simulate updating data after replenishment
          product.totalStock += 20; // Assume adding 20 units each time
          
          // If stock is now above safety stock, remove from warning list
          if (product.totalStock > product.safeStock) {
            const index = lowStockProducts.value.findIndex(item => item.id === productId);
            if (index !== -1) {
              lowStockProducts.value.splice(index, 1);
            }
          }
          
          uni.hideLoading();
          uni.showToast({
            title: '补货成功',
            icon: 'success'
          });
        }, 1000);
      }
    }
  });
};

// Remove product modal variables
const confirmRemoveProduct = (product) => {
  uni.showModal({
    title: '移除商品确认',
    content: `确定要从货架移除商品"${product.name}"吗？`,
    success: (res) => {
      if (res.confirm) {
        openRemoveProductModal(product);
      }
    }
  });
};

// Open remove product modal
const openRemoveProductModal = (product) => {
  removeProductForm.shelfId = selectedShelfId.value;
  removeProductForm.productId = product.productId || product.id;
  removeProductForm.productName = product.name;
  removeProductForm.currentQuantity = product.quantity || 0;
  removeProductForm.removeQuantity = 1;
  removeProductForm.reason = '';
  removeProductForm.rfidTags = [];
  
  showRemoveProductModal.value = true;
};

// Close remove product modal
const closeRemoveProductModal = () => {
  showRemoveProductModal.value = false;
  
  // Reset form
  removeProductForm.shelfId = null;
  removeProductForm.productId = null;
  removeProductForm.productName = '';
  removeProductForm.currentQuantity = 0;
  removeProductForm.removeQuantity = 1;
  removeProductForm.reason = '';
  removeProductForm.rfidTags = [];
};

// Submit remove product
const submitRemoveProduct = async () => {
  if (!removeProductForm.productId || !removeProductForm.shelfId) {
    uni.showToast({
      title: '参数错误',
      icon: 'none'
    });
    return;
  }
  
  if (removeProductForm.removeQuantity <= 0 || removeProductForm.removeQuantity > removeProductForm.currentQuantity) {
    uni.showToast({
      title: '移除数量无效',
      icon: 'none'
    });
    return;
  }
  
  uni.showLoading({
    title: '移除中...'
  });
  
  try {
    const params = new URLSearchParams();
    if (removeProductForm.removeQuantity) {
      params.append('quantity', removeProductForm.removeQuantity.toString());
    }
    if (removeProductForm.reason) {
      params.append('reason', removeProductForm.reason);
    }
    
    const url = `/api/shelves/${removeProductForm.shelfId}/products/${removeProductForm.productId}${params.toString() ? '?' + params.toString() : ''}`;
    
    const requestOptions = {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json'
      }
    };
    
    // 如果有RFID标签，添加到请求体中
    if (removeProductForm.rfidTags && removeProductForm.rfidTags.length > 0) {
      requestOptions.body = JSON.stringify(removeProductForm.rfidTags);
    }
    
    console.log('移除商品请求:', url, requestOptions);
    
    const response = await http.delete(url, {
      data: removeProductForm.rfidTags.length > 0 ? removeProductForm.rfidTags : undefined,
      params: {
        quantity: removeProductForm.removeQuantity,
        reason: removeProductForm.reason || '人工移除'
      }
    });
    
    console.log('移除商品响应:', response);
    
    if (response.code === 200) {
      uni.showToast({
        title: '移除成功',
        icon: 'success'
      });
      
      // Close modal
      closeRemoveProductModal();
      
      // Refresh shelf products
      if (showShelfProductsModal.value && selectedShelfId.value) {
        fetchShelfProducts(selectedShelfId.value, shelfProductsPagination.current);
      }
      
    } else {
      uni.showToast({
        title: response.msg || '移除失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('移除商品失败:', error);
    uni.showToast({
      title: '移除失败，请重试',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// Add RFID tag
const addRfidTag = () => {
  const newTag = removeProductForm.newRfidTag?.trim();
  if (newTag && !removeProductForm.rfidTags.includes(newTag)) {
    removeProductForm.rfidTags.push(newTag);
    removeProductForm.newRfidTag = '';
  }
};

// Remove RFID tag
const removeRfidTag = (index) => {
  removeProductForm.rfidTags.splice(index, 1);
};

// Execute when page loads
onMounted(async () => {
  console.log('零售货架系统商家仪表盘页面加载完成');
  // Get status bar height
  getStatusBarHeight();

  // Initialize user state
  userStore.initUserState();
  
  if (userStore.isLoggedIn) {
      // Get all product data
      await fetchAllProducts();
      
      // Get shelves data
      await fetchShelves();
    }

  // If user is not a merchant, prompt to switch identity
  if (0) {
    uni.showModal({
      title: '提示',
      content: '您当前不是商家身份，是否切换为商家身份？',
      success: (res) => {
        if (res.confirm) {
          // Simulate merchant login
          const merchantInfo = {
            id: 'M' + Math.floor(Math.random() * 10000),
            username: '示例商家',
            storeName: '智能货架管理中心',
            phone: '13800138000'
          };
          userStore.login('merchant', merchantInfo);
        } else {
          // User canceled, return to user home page
          uni.redirectTo({
            url: '/pages/index/index'
          });
        }
      }
    });
  }

  // Get all product data
  await fetchAllProducts();
  
  // Get shelves data
  await fetchShelves();
});
</script>

<style>
.dashboard-container {
  padding-bottom: 120rpx; /* Add bottom padding for bottom navigation bar */
  background-color: #FFF9F2; /* Same background color as home page */
  min-height: 100vh;
}

/* 添加未登录时的样式 */
.login-required-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #FFF9F2;
  padding: 40rpx;
}

.login-required-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #FFFFFF;
  border-radius: 16rpx;
  padding: 60rpx 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 600rpx;
}

.login-required-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
  margin-top: 30rpx;
  margin-bottom: 20rpx;
}

.login-required-desc {
  font-size: 28rpx;
  color: #666666;
  text-align: center;
  margin-bottom: 40rpx;
}

.login-btn {
  background-color: #FF8C42;
  color: #FFFFFF;
  font-size: 32rpx;
  font-weight: bold;
  padding: 20rpx 60rpx;
  border-radius: 40rpx;
}

.page-header {
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #FFFFFF;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  border-bottom: 1rpx solid #FFE6CC; /* Same border as home page */
}

.title-section {
  display: flex;
  flex-direction: column;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
}

.date {
  font-size: 24rpx;
  color: #999999;
  margin-top: 6rpx;
}

.refresh-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #FFF0E0; /* Same button background color as home page */
  border-radius: 30rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding: 0 30rpx;
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333333;
  position: relative;
  padding-left: 20rpx;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 6rpx;
  height: 30rpx;
  background-color: #FF8C42; /* Same accent color as home page */
  border-radius: 3rpx;
}

.view-all {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #999999;
}

.stats-overview {
  padding: 20rpx 30rpx;
}

.stats-grid {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10rpx;
}

.stat-card {
  width: calc(50% - 20rpx);
  margin: 10rpx;
  background-color: #FFFFFF;
  border-radius: 16rpx;
  padding: 20rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  border: 1rpx solid #FFE6CC; /* Same border as home page */
}

.stat-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 20rpx;
}

.machine-icon, .product-icon, .sales-icon, .warning-icon {
  background-color: #FFF0E0; /* Same icon background color as home page */
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 24rpx;
  color: #666666;
  display: block;
  margin-bottom: 10rpx;
}

.stat-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
  display: block;
}

/* Shelves section */
.shelves-section {
  margin-top: 30rpx;
  padding-bottom: 20rpx;
}

/* Add new shelf button */
.add-shelf-btn {
  margin: 0 30rpx 20rpx;
  height: 70rpx;
  background-color: #FF8C42;
  border-radius: 35rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #FFFFFF;
  font-size: 28rpx;
  font-weight: bold;
}

.add-shelf-btn uni-icons {
  margin-right: 10rpx;
}

/* Shelf search box */
.shelf-search-box {
  margin: 0 30rpx 20rpx;
}

.search-box {
  height: 70rpx;
  background-color: #FFFFFF;
  border-radius: 35rpx;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  border: 1rpx solid #FFE6CC;
}

.search-box uni-icons {
  margin-right: 10rpx;
}

.search-box input {
  flex: 1;
  height: 70rpx;
  font-size: 28rpx;
}

.clear-search {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 20rpx;
}

/* Shelf search result */
.shelf-search-result {
  padding: 0 30rpx;
  margin-bottom: 20rpx;
}

.shelves-list {
  padding: 0 30rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.shelf-card {
  background-color: #FFFFFF;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  border: 1rpx solid #FFE6CC;
}

.shelf-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.shelf-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333333;
}

.shelf-status {
  font-size: 22rpx;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.status-online {
  background-color: #D1FAE5;
  color: #10B981;
}

.status-offline {
  background-color: #F3F4F6;
  color: #6B7280;
}

.shelf-location {
  font-size: 24rpx;
  color: #666666;
  margin-bottom: 15rpx;
}

.shelf-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15rpx;
}

.shelf-stat {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.shelf-stat .stat-label {
  font-size: 20rpx;
  margin-bottom: 5rpx;
}

.shelf-stat .stat-value {
  font-size: 26rpx;
}

.stock-bar {
  height: 8rpx;
  background-color: #FFE6CC; /* Same progress bar background color as home page */
  border-radius: 4rpx;
  overflow: hidden;
}

.stock-progress {
  height: 100%;
  border-radius: 4rpx;
}

/* Shelf actions */
.shelf-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 15rpx;
  gap: 10rpx;
}

.shelf-action-btn {
  display: flex;
  align-items: center;
  padding: 8rpx 16rpx;
  background-color: #FFF0E0;
  border-radius: 20rpx;
  border: 1rpx solid #FFE6CC;
}

.shelf-action-btn text {
  font-size: 22rpx;
  color: #FF8C42;
  margin-left: 6rpx;
}

.shelf-action-btn.restock-btn {
  background-color: #ECFDF5;
  border: 1rpx solid #D1FAE5;
}

.shelf-action-btn.restock-btn text {
  color: #10B981;
}

.shelf-action-btn.delete-btn {
  background-color: #FEE2E2;
  border: 1rpx solid #FECACA;
}

.shelf-action-btn.delete-btn text {
  color: #EF4444;
}

/* Product search section */
.products-section {
  margin-top: 30rpx;
}

/* Search results */
.search-results {
  background-color: #FFFFFF;
  border-radius: 16rpx;
  margin: 0 30rpx;
  padding: 10rpx 0;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  border: 1rpx solid #FFE6CC;
}

.search-result-item {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #FFE6CC;
}

.search-result-item:last-child {
  border-bottom: none;
}

.result-image {
  width: 80rpx;
  height: 80rpx;
  border-radius: 10rpx;
  background-color: #FFF0E0;
  margin-right: 20rpx;
}

.result-info {
  flex: 1;
}

.result-name {
  font-size: 28rpx;
  color: #333333;
  margin-bottom: 6rpx;
}

.result-category {
  font-size: 22rpx;
  color: #999999;
}

.result-price {
  font-size: 28rpx;
  font-weight: bold;
  color: #FF8C42;
}

/* Searching status and no results */
.search-loading, .no-results {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx 0;
  background-color: #FFFFFF;
  border-radius: 16rpx;
  margin: 0 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  border: 1rpx solid #FFE6CC;
}

.search-loading text, .no-results text {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #999999;
}

/* Product sales comparison section */
.products-list {
  background-color: #FFFFFF;
  border-radius: 16rpx;
  margin: 0 30rpx;
  padding: 0;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  border: 1rpx solid #FFE6CC;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  position: relative;
  border-bottom: 1rpx solid #FFE6CC; /* Same separator as home page */
}

.product-item:last-child {
  border-bottom: none;
}

/* Ranking container */
.product-rank-container {
  width: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 20rpx;
}

.product-rank {
  width: 40rpx;
  height: 40rpx;
  background-color: #FFF0E0; /* Same background color as home page */
  border-radius: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24rpx;
  font-weight: bold;
  color: #FF8C42; /* Same text color as home page */
  margin-right: 20rpx;
}

/* Special style for top three */
.product-item:nth-child(1) .product-rank {
  background-color: #FF8C42;
  color: #FFFFFF;
  width: 50rpx;
  height: 50rpx;
  font-size: 28rpx;
}

.product-item:nth-child(2) .product-rank {
  background-color: #FFC08D;
  color: #FFFFFF;
}

.product-item:nth-child(3) .product-rank {
  background-color: #FFE6CC;
  color: #FF8C42;
}

/* Product image */
.product-image {
  width: 100rpx;
  height: 100rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
  background-color: #FFF0E0;
  flex-shrink: 0;
}

/* Product info */
.product-info {
  flex: 1;
  margin-right: 20rpx;
  min-width: 0; /* Prevent content overflow */
}

.product-name {
  font-size: 28rpx;
  color: #333333;
  margin-bottom: 8rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-category {
  font-size: 22rpx;
  color: #666666;
}

.product-sales {
  margin-right: 20rpx;
  text-align: right;
  min-width: 60rpx;
}

.sales-value {
  font-size: 28rpx;
  font-weight: bold;
  color: #FF8C42; /* Same accent color as home page */
}

.sales-label {
  font-size: 22rpx;
  color: #666666;
  margin-left: 5rpx;
}

.sales-bar-container {
  height: 8rpx;
  background-color: #FFE6CC;
  border-radius: 4rpx;
  overflow: hidden;
  margin-top: 10rpx;
}

.sales-bar {
  height: 100%;
  background-color: #FF8C42;
  border-radius: 4rpx;
  transition: width 0.3s ease;
}

/* Low stock warning section */
.warning-section {
  margin-top: 30rpx;
  margin-bottom: 30rpx;
}

.warning-list {
  background-color: #FFFFFF;
  border-radius: 16rpx;
  margin: 0 30rpx;
  padding: 10rpx 0;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  border: 1rpx solid #FFE6CC; /* Same border as home page */
}

.warning-item {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #FFE6CC; /* Same separator as home page */
}

.warning-item:last-child {
  border-bottom: none;
}

.warning-image {
  width: 60rpx;
  height: 60rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
  background-color: #FFF0E0; /* Same background color as home page */
}

.warning-info {
  flex: 1;
  margin-right: 20rpx;
}

.warning-name {
  font-size: 28rpx;
  color: #333333;
  margin-bottom: 5rpx;
}

.warning-location {
  font-size: 22rpx;
  color: #666666;
}

.warning-stock {
  margin-right: 20rpx;
  text-align: right;
}

.warning-value {
  font-size: 28rpx;
  font-weight: bold;
  color: #EF4444;
}

.warning-label {
  font-size: 22rpx;
  color: #666666;
  margin-left: 5rpx;
}

.replenish-btn {
  padding: 10rpx 20rpx;
  background-color: #FFF0E0; /* Same button background color as home page */
  color: #FF8C42; /* Same button text color as home page */
  font-size: 24rpx;
  border-radius: 30rpx;
  border: 1rpx solid #FFE6CC;
}

/* Modal styles */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  width: 90%;
  max-height: 80vh;
  background-color: #FFFFFF;
  border-radius: 16rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.modal-header {
  padding: 20rpx 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #FFE6CC;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.modal-close {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-body {
  flex: 1;
  overflow-y: auto;
  padding: 20rpx 0;
}

.modal-loading, .modal-error, .modal-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 0;
}

.modal-loading text, .modal-error text, .modal-empty text {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #999999;
}

.retry-btn {
  margin-top: 20rpx;
  padding: 10rpx 30rpx;
  background-color: #FFF0E0;
  border-radius: 30rpx;
  border: 1rpx solid #FFE6CC;
}

.retry-btn text {
  font-size: 24rpx;
  color: #FF8C42;
  margin-top: 0;
}

/* Shelf products list */
.shelf-products-list {
  padding: 0 20rpx;
}

.shelf-product-item {
  display: flex;
  padding: 20rpx;
  border-bottom: 1rpx solid #FFE6CC;
  position: relative;
}

.shelf-product-item:last-child {
  border-bottom: none;
}

.shelf-product-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  background-color: #FFF0E0;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.shelf-product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.shelf-product-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 8rpx;
}

.shelf-product-description {
  font-size: 24rpx;
  color: #666666;
  margin-bottom: 16rpx;
  flex: 1;
}

.shelf-product-details {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.shelf-product-price {
  font-size: 28rpx;
  font-weight: bold;
  color: #FF8C42;
}

.shelf-product-stock {
  font-size: 24rpx;
  color: #666666;
}

.shelf-product-position {
  font-size: 22rpx;
  color: #999999;
}

.shelf-product-actions {
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin-left: 10rpx;
}

.shelf-product-action-btn {
  display: flex;
  align-items: center;
  padding: 6rpx 12rpx;
  background-color: #ECFDF5;
  border-radius: 16rpx;
  border: 1rpx solid #D1FAE5;
}

.shelf-product-action-btn text {
  font-size: 20rpx;
  color: #10B981;
  margin-left: 4rpx;
}

.low-stock {
  color: #EF4444;
  font-weight: bold;
}

/* Modal pagination */
.modal-pagination {
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #FFE6CC;
  background-color: #F9FAFB;
}

.pagination-info {
  text-align: center;
  margin-bottom: 15rpx;
}

.pagination-info text {
  font-size: 24rpx;
  color: #666666;
}

.pagination-controls {
  display: flex;
  justify-content: center;
  gap: 20rpx;
}

.pagination-btn {
  padding: 10rpx 20rpx;
  background-color: #FF8C42;
  color: #FFFFFF;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.pagination-btn.disabled {
  background-color: #E5E7EB;
  color: #9CA3AF;
}

/* Restock modal styles */
.product-selector {
  height: 80rpx;
  background-color: #F9FAFB;
  border: 1rpx solid #E5E7EB;
  border-radius: 8rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.selected-product {
  font-size: 28rpx;
  color: #333333;
}

.placeholder-text {
  font-size: 28rpx;
  color: #9CA3AF;
}

.form-textarea {
  width: 100%;
  min-height: 120rpx;
  background-color: #F9FAFB;
  border: 1rpx solid #E5E7EB;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333333;
  resize: vertical;
}

/* Product selector modal */
.product-selector-list {
  max-height: 400rpx;
  overflow-y: auto;
  padding: 0 20rpx;
}

.product-selector-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #FFE6CC;
  position: relative;
}

.product-selector-item:last-child {
  border-bottom: none;
}

.product-selector-image {
  width: 80rpx;
  height: 80rpx;
  border-radius: 10rpx;
  background-color: #FFF0E0;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.product-selector-info {
  flex: 1;
}

.product-selector-name {
  font-size: 28rpx;
  color: #333333;
  margin-bottom: 6rpx;
}

.product-selector-description {
  font-size: 22rpx;
  color: #666666;
  margin-bottom: 6rpx;
}

.product-selector-price {
  font-size: 26rpx;
  font-weight: bold;
  color: #FF8C42;
}

.product-selector-stock {
  font-size: 22rpx;
  color: #999999;
  margin-top: 4rpx;
}

.product-selected-icon {
  position: absolute;
  right: 20rpx;
  top: 50%;
  transform: translateY(-50%);
}

/* Create shelf form styles */
.form-group {
  margin-bottom: 20rpx;
  padding: 0 30rpx;
}

.form-label {
  font-size: 26rpx;
  color: #666666;
  margin-bottom: 10rpx;
  display: block;
}

.form-input {
  width: 100%;
  height: 80rpx;
  background-color: #F9FAFB;
  border: 1rpx solid #E5E7EB;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333333;
}

.form-input:disabled {
  background-color: #F3F4F6;
  color: #9CA3AF;
}

.form-textarea:disabled {
  background-color: #F3F4F6;
  color: #9CA3AF;
}

.radio-group {
  display: flex;
  gap: 30rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.radio-button {
  width: 36rpx;
  height: 36rpx;
  border-radius: 18rpx;
  border: 1rpx solid #E5E7EB;
  display: flex;
  justify-content: center;
  align-items: center;
}

.radio-selected {
  position: relative;
  border-color: #FF8C42;
}

.radio-selected::after {
  content: '';
  width: 20rpx;
  height: 20rpx;
  border-radius: 10rpx;
  background-color: #FF8C42;
  position: absolute;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #FFE6CC;
  margin-top: 20rpx;
}

.form-btn {
  padding: 15rpx 30rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  font-weight: bold;
}

.cancel-btn {
  background-color: #F3F4F6;
  color: #6B7280;
}

.submit-btn {
  background-color: #FF8C42;
  color: #FFFFFF;
}

.submit-btn.disabled {
  background-color: #E5E7EB;
  color: #9CA3AF;
}

.delete-confirm-btn {
  background-color: #EF4444;
  color: #FFFFFF;
}

/* Confirm modal */
.confirm-modal {
  max-height: 50vh;
}

.confirm-message {
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  gap: 20rpx;
}

.confirm-message text {
  font-size: 28rpx;
  color: #333333;
  line-height: 1.5;
}

/* Remove product button */
.shelf-product-action-btn.remove-btn {
  background-color: #FEE2E2;
  border: 1rpx solid #FECACA;
  margin-top: 8rpx;
}

.shelf-product-action-btn.remove-btn text {
  color: #EF4444;
}

/* Remove product modal styles */
.quantity-info {
  display: flex;
  align-items: baseline;
  padding: 20rpx;
  background-color: #F9FAFB;
  border-radius: 8rpx;
  border: 1rpx solid #E5E7EB;
}

.quantity-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
  margin-right: 8rpx;
}

.quantity-unit {
  font-size: 24rpx;
  color: #666666;
}

.form-hint {
  font-size: 22rpx;
  color: #9CA3AF;
  margin-top: 8rpx;
  display: block;
}

.rfid-input-section {
  display: flex;
  gap: 10rpx;
  align-items: center;
}

.rfid-input {
  flex: 1;
}

.add-rfid-btn {
  display: flex;
  align-items: center;
  padding: 10rpx 16rpx;
  background-color: #ECFDF5;
  border-radius: 8rpx;
  border: 1rpx solid #D1FAE5;
  gap: 6rpx;
}

.add-rfid-btn text {
  font-size: 24rpx;
  color: #10B981;
}

.rfid-tags-list {
  margin-top: 16rpx;
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
}

.rfid-tag-item {
  display: flex;
  align-items: center;
  padding: 8rpx 12rpx;
  background-color: #F3F4F6;
  border-radius: 20rpx;
  border: 1rpx solid #E5E7EB;
  gap: 8rpx;
}

.rfid-tag-text {
  font-size: 22rpx;
  color: #374151;
}

.remove-rfid-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24rpx;
  height: 24rpx;
  border-radius: 12rpx;
  background-color: #FEE2E2;
}

.remove-confirm-btn {
  background-color: #EF4444;
  color: #FFFFFF;
}
</style>

